﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using FytSoa.Common;
using FytSoa.Core.Model;
using FytSoa.Service.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace FytSoa.Api.Controllers.App
{
    [Route("api/app/[controller]/[action]")]
    [ApiController]
    public class FilesController : ControllerBase
    {
        private readonly IMemberService _ownerService;
        private readonly ITourGuideOrderService _orderService;
        public FilesController(IMemberService ownerService
        , ITourGuideOrderService orderService)
        {
            _ownerService = ownerService;
            _orderService = orderService;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Upload(List<IFormFile> file)
        {
            var guid = Request.Form["guid"].ToString();
            var type = Convert.ToInt32(Request.Form["type"]);

            //原文件名
            var filename = file[0].FileName;
            //扩展名
            var fileExt = FileHelper.GetFileExt(filename);
            //新的文件名字
            filename = Guid.NewGuid() + "." + fileExt;
            //根据类型创建文件夹
            var path = Utils.AssigendPath(fileExt, "wwwroot");
            //检查物理路径是否存在 不存在则创建
            FileHelperCore.CreateFiles(path);
            using (var stream = new FileStream(path + filename, FileMode.Create))
            {
                file[0].CopyTo(stream);
                stream.Flush();
            }
            var newFilePath = path.Replace("wwwroot", "") + filename;
            if (type == 1)
            {
                //上传头像
                await _ownerService.UpdateAsync(m => new Core.Model.Member.Member() { HeadPic = newFilePath },
                m => m.Guid == guid);
            }

            if (type==2)
            {
                //上传文件
                var omodel=await _orderService.GetModelAsync(m=>m.Guid==guid);
                if (omodel.data!=null)
                {
                    omodel.data.ImageList.Add(new ImagesModel() { url = newFilePath });
                    await _orderService.UpdateAsync(omodel.data);
                }
                
            }
            return Ok(new ApiResult<string>() { data = newFilePath });
        }
    }
}